package com.kc.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author TP
 * @date 2021-02-06 10:15
 */
public class EncryptUtils {

    /**
     * 把所有元素排序, 并按照“参数=参数值”的模式用“&”字符拼接成字符串,作为待签名的字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @param encode 是否需要urlEncode
     * @return
     */
    public static String createLinkString(Map params, boolean encode) {

        try {
            List<String> keys = new ArrayList<>(params.keySet());
            //对key进行排序
            Collections.sort(keys);
            StringBuilder builder = new StringBuilder();
            Object object = params.get("_input_charset");
            String charset = object == null ? "utf-8" : object.toString();
            for (String key : keys) {
                Object value = params.get(key);
                if (value == null || "".equals(value)) {
                    continue;
                }
                builder.append(key).append("=");
                if (encode) {
                    builder.append(URLEncoder.encode(value.toString(), charset));
                } else {
                    builder.append(value);
                }
                builder.append("&");
            }
            //去掉最后一位的符号
            if (builder.length() > 0) {
                builder.deleteCharAt(builder.length() - 1);
            }
            return builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
